// 云函数入口文件
const cloud = require("wx-server-sdk");
const isTypeDanger = require("./isTypeDanger.js");
cloud.init();
const db = cloud.database();

function insertXin(Xin) {
    const perfect = {
        ...Xin,
        ...{
            isVisible: Xin.date <= new Date().getTime(),
            // 心语签可不可视，公开的时候没到日期不能公开
            updateTime: new Date(),
        },
    };

    if (Xin.hasOwnProperty("_id")) {
        // _id 不能被更新，所以需要删除
        const _id = Xin._id;
        delete perfect._id;
        return db.collection("UnPublicXin").doc(_id).update({
            data: perfect,
        });
    } else {
        return db.collection("UnPublicXin").add({
            data: {
                ...perfect,
                ...{
                    createTime: new Date(),
                },
            },
        });
    }
}

exports.main = async (event, context) => {
    if (!event.hasOwnProperty("Xin"))
        return {
            err: JSON.stringify(event),
            desc: "Xin 属性不存在",
        };
    try {
        event.Xin.date = new Date(event.Xin.date).getTime();
    } catch (err) {
        return { err: JSON.stringify(event), desc: "Date 格式错误" };
    }

    const err = isTypeDanger(event, {
        Xin: {
            date: "Number",
            title: "String",
            description: "String",
            please: "String",
            image: "String",
            tags: ["String"],
            belongTo: "String", // 心语签归属的章节
            type: "String",
        },
    });
    if (err) return { err, desc: "参数解析错误" };
    if (!event.Xin._openid) event.Xin._openid = event.userInfo.openId;

    // 重复数据更新问题
    try {
        return await insertXin(event.Xin);
    } catch (err) {
        return { err, desc: "插入数据错误" };
    }
};
